package com.xiaoyu.merchant.ui.fragment.main;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.NestedScrollView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.xiaoyu.commonlib.network.CommonHttpResponser;
import com.xiaoyu.commonlib.ui.widget.AutofitHeightViewPager;
import com.xiaoyu.commonlib.utils.CCircleImageView;
import com.xiaoyu.commonlib.utils.CommonFragmentPagerAdapter;
import com.xiaoyu.commonlib.utils.PreferencesUtil;
import com.xiaoyu.commonlib.utils.ToastUtil;
import com.xiaoyu.commonlib.utils.UIUtils;
import com.xiaoyu.commonlib.utils.ViewPagerUtils;
import com.xiaoyu.merchant.MerchantConstants;
import com.xiaoyu.merchant.R;
import com.xiaoyu.merchant.model.StoreDetailBean;
import com.xiaoyu.merchant.network.NetworkManager;
import com.xiaoyu.merchant.ui.activity.ModificationDataActivity;
import com.xiaoyu.merchant.ui.activity.set.SetActivity;
import com.xiaoyu.merchant.ui.fragment.store.StoreCommentsFragment;
import com.xiaoyu.merchant.ui.fragment.store.StoreIntroductionFragment;
import com.xiaoyu.merchant.ui.fragment.store.StoreProductFragment;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * @author jx
 * @date 创建时间 2018/12/29
 * @Description 店铺管理
 */
public class StoreFragment extends Fragment implements View.OnClickListener {
    private View mView;

    @BindView(R.id.activity_store_background_img)
    ImageView backgroundImg;//顶部背景
    @BindView(R.id.activity_store_img)
    CCircleImageView storeImg;//头像
    @BindView(R.id.activity_store_name)
    TextView storeName;//昵称
    @BindView(R.id.activity_store_score)
    TextView storeScore;//评分
    @BindView(R.id.activity_store_sales)
    TextView storeSales;//销量
    @BindView(R.id.activity_store_score_sales)
    LinearLayout mScoreSales;
    @BindView(R.id.activity_store_function_layout)
    LinearLayout functionLayout;//导航栏
    @BindView(R.id.activity_store_line)
    View mLine;//导航栏标示线
    public static AutofitHeightViewPager mViewPager;
    @BindView(R.id.activity_store_scroll_view)
    NestedScrollView mScrollView;//滚动控件
    @BindView(R.id.top_title_bar)
    RelativeLayout mTitleBar;//顶部导航栏

    private ViewPagerUtils pagerUtils;
    private CommonFragmentPagerAdapter mPagerAdapter;
    private List<Fragment> mFragmentList = new ArrayList<>();
    private float maxHeight;//最大滚动高度

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        if (mView == null) {
            mView = inflater.inflate(R.layout.fragment_store, container, false);
            //绑定fragment
            ButterKnife.bind(this, mView);
            initView();
        }
        ViewGroup parent = (ViewGroup) mView.getParent();
        if (parent != null) {
            parent.removeView(mView);
        }
        return mView;

    }

    @Override
    public void onResume() {
        super.onResume();
        getStoreInfo();
    }

    private void initView() {
        mViewPager = mView.findViewById(R.id.activity_store_view_page);
        //商家背景
        backgroundImg.setFocusable(true);
        backgroundImg.setFocusableInTouchMode(true);
        backgroundImg.requestFocus();
        //中部功能导航栏
        pagerUtils = new ViewPagerUtils(getActivity(), functionLayout, mLine);
        pagerUtils.initLine(UIUtils.dip2px(50));
        pagerUtils.setTextColor("#333333", "#1772e5");
        pagerUtils.selectItem(0);

        for (int i = 0; i < functionLayout.getChildCount(); i++) {
            functionLayout.getChildAt(i).setOnClickListener(this);
        }

        //ViewPager
        mPagerAdapter = new CommonFragmentPagerAdapter(getFragmentManager(), mFragmentList);
        mViewPager.setAdapter(mPagerAdapter);
        mViewPager.addOnPageChangeListener(onPageChangeListener);
        mViewPager.setCurrentItem(2);

        //ScrollView和titleBar
        mTitleBar.getBackground().setAlpha(0);
        mScrollView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                maxHeight = backgroundImg.getHeight();
                mScrollView.setOnScrollChangeListener(new NestedScrollView.OnScrollChangeListener() {
                    @Override
                    public void onScrollChange(NestedScrollView v, int scrollX, int scrollY, int oldScrollX, int oldScrollY) {
                        if (scrollY <= 0) {
                            mTitleBar.getBackground().setAlpha(0);
                        } else if (scrollY < maxHeight) {
                            float scale = scrollY / maxHeight;
                            mTitleBar.getBackground().setAlpha((int) (scale * 255));
                        } else {
                            mTitleBar.getBackground().setAlpha(255);
                        }
                    }
                });
            }
        });

    }

    @Override
    public void onClick(View v) {
        if (v == functionLayout.getChildAt(0)) {//产品
            pagerUtils.scrollLineMove(0, 0);
            pagerUtils.selectItem(0);
            mViewPager.setCurrentItem(0);
            mViewPager.updateHeight(0);
        } else if (v == functionLayout.getChildAt(1)) {//评价
            pagerUtils.scrollLineMove(1, 0);
            pagerUtils.selectItem(1);
            mViewPager.setCurrentItem(1);
            mViewPager.updateHeight(1);
        } else if (v == functionLayout.getChildAt(2)) {//商家
            pagerUtils.scrollLineMove(2, 0);
            pagerUtils.selectItem(2);
            mViewPager.setCurrentItem(2);
            mViewPager.updateHeight(2);
        }
    }

    /**
     * ViewPager滑动监听
     */
    private ViewPager.OnPageChangeListener onPageChangeListener = new ViewPager.OnPageChangeListener() {
        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
            pagerUtils.scrollLineMove(position, positionOffset);
        }

        @Override
        public void onPageSelected(int position) {
            mViewPager.updateHeight(position);
            pagerUtils.scrollLineMove(position, 0);
            pagerUtils.selectItem(position);
        }

        @Override
        public void onPageScrollStateChanged(int state) {

        }
    };

    //设置
    @OnClick(R.id.fragment_store_set)
    public void storeSetClick() {
        startActivity(new Intent(getActivity(), SetActivity.class));
    }

    //点击进入商铺信息页面
    @OnClick(R.id.activity_store_img)
    public void personalClick() {
        startActivity(new Intent(getActivity(), ModificationDataActivity.class));
    }


    private void getStoreInfo() {
        NetworkManager.getStoreInfo(PreferencesUtil.getString(PreferencesUtil.TOKEN, ""), new CommonHttpResponser() {
            @Override
            public void onSuccess(String result) {
                Log.i("jx", "获取店铺信息  getStoreInfo   onSuccess ： " + result);
                parseStoreInfoSuc(result);
            }

            @Override
            public void onFailed(String errorCode, String errorDiscription) {
                ToastUtil.logError("商家详情", errorCode, errorDiscription);
            }
        });
    }

    private void parseStoreInfoSuc(String result) {
        ToastUtil.logResult("商家详情", result);
        StoreDetailBean bean = new Gson().fromJson(result, StoreDetailBean.class);
        Glide.with(this).load(bean.getData().getStoreackground()).into(backgroundImg);//顶部背景
        Glide.with(this).load(bean.getData().getStoreimg()).into(storeImg);//商家头像
        storeName.setText(bean.getData().getStorename());//商家名称
        storeScore.setText("评分" + bean.getData().getAvg());//评分
        storeSales.setText("销量" + bean.getData().getStoresales());//销量

        initFragment(bean.getData());
    }

    private void initFragment(StoreDetailBean.DataBean data) {
        StoreProductFragment productFragment = new StoreProductFragment();
        Bundle pBundle = new Bundle();
        pBundle.putSerializable(MerchantConstants.MERCHANT_INFO, data);
        pBundle.putInt(AutofitHeightViewPager.POSITION, 0);
        productFragment.setArguments(pBundle);
        StoreCommentsFragment commentsFragment = new StoreCommentsFragment();
        Bundle cBundle = new Bundle();
        cBundle.putSerializable(MerchantConstants.MERCHANT_INFO, data);
        cBundle.putInt(AutofitHeightViewPager.POSITION, 1);
        commentsFragment.setArguments(cBundle);
        StoreIntroductionFragment introductionFragment = new StoreIntroductionFragment();
        Bundle iBundle = new Bundle();
        iBundle.putSerializable(MerchantConstants.MERCHANT_INFO, data);
        iBundle.putInt(AutofitHeightViewPager.POSITION, 2);
        introductionFragment.setArguments(iBundle);
        mFragmentList.clear();
        mFragmentList.add(productFragment);
        mFragmentList.add(commentsFragment);
        mFragmentList.add(introductionFragment);
        mPagerAdapter.updateList(mFragmentList);
    }

}
